package com.fili.core.sources;

import com.fili.core.utils.RelativePath;
import com.fili.core.utils.PathTrimmer;

import java.io.*;
import java.util.ArrayList;

/**
 * Created by Claudiu-Florin FILIMON
 * Date: Nov 16, 2006
 * Time: 5:46:25 PM
 * Revision: 0
 */
public class MappedSource
{
    private SourceMapper source;
    private int smallFile;
    private String sourcePath;
    private String[] lines;
    private int[] mappings;


    public int getSize()
    {
        return lines.length;
    }

    public String getSourcePath()
    {
        return sourcePath;
    }

    public String getLine(int i)
    {
        if (i < lines.length)
            return lines[i];
        return null;
    }

    public int getMapping(int i)
    {
        if (i < mappings.length)
            return mappings[i];
        return -1;
    }

    public boolean isMapped(int i)
    {
        return (getMapping(i) >= 0);
    }

    public MappedSource(int smallFile, String sourcePath, SourceMapper source) throws IOException
    {
        this.smallFile = smallFile;
        this.sourcePath = sourcePath;
        this.source = source;
        parseFile(source);
    }

    private void parseFile(SourceMapper source) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(sourcePath)));
        ArrayList lns = new ArrayList();

        String line;

        while ((line = br.readLine()) != null)
        {
            lns.add(line);
        }

        lines = new String[lns.size()];
        mappings = new int[lns.size()];
        for (int i = 0; i < lines.length; i++)
        {
            lines[i] = (String) lns.get(i);
            LocationMapping lm = source.mapFrom(smallFile, i + 1);
            if (lm != null)
                mappings[i] = lm.getBigLine();
            else
                mappings[i] = -1;
        }

        lns.clear();
    }


    public String toString()
    {
//        return RelativePath.getRelativePath(new File(source.getSourcePath()), new File(sourcePath));
        return PathTrimmer.getFileName(sourcePath);
    }
}
